import React, { useState, useEffect, useRef } from 'react';
import { useRequest, useModel } from 'umi';
import { Row, Col, Card, Tabs, Descriptions, Divider, message,Collapse,Radio} from 'antd';
import { getMonitoringDevicInfo, getEChartsOption, getMonitoringPhase } from '@/services/deviceLive';
import { queryDeviceAlarm } from '@/services/deviceAlarm';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import moment from 'moment'
import ECharts from 'echarts-for-react';
import UpdateForm from '@/pages/alarm/record/components/UpdateForm';

import RunData from '../runData';

const { Panel } = Collapse;
import styles from './index.less';
const { TabPane } = Tabs;
import { updateDeviceAlarm } from '@/services/deviceAlarm';

/**
 * 更新节点
 * @param fields
 */
 const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceAlarm(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

const details: React.FC = (props: any) => {
  const { type,id } = props.match.params;
 
  const second = useRequest(() => {
    return getMonitoringPhase({id,type});
  });

  const [deviceInfo, setDeviceInfo] = useState<API.DeviceItem>({});
  const [runningData, setRunningData] = useState({});
  const [alarmSourceEnumDict, setAlarmSourceEnumDict] = useState({});
  const [alarmCategoryEnumDict, setAlarmCategoryEnumDict] = useState({});
  const [alarmLevelEnumDict, setAlarmLevelEnumDict] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [chartIndex, setChartIndex] = useState(0);



  const actionRef = useRef<ActionType>();

  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts } = initialState || {};
  if (mySocket) {
      mySocket.send({id});
      mySocket.onmessage =async function (e) {
        console.log(`onmessage: ${e.data}`);
        //排除心跳数据
        if ("heartbeat" != e.data&&e.data.indexOf("RunningData")!=-1) {
          onMessage(e);
        }else if ("heartbeat" != e.data&&e.data.indexOf("AlarmData")!=-1) {
          const data = JSON.parse(e.data);
          await setInitialState((s) => ({ ...s, alarmNotices: data.AlarmData }));
        }
      };
  }

  const onMessage = (e:any) => {
    const message = JSON.parse(e.data);
   // const runningData = {...message.RunningData, ...message.ReliabilityData}
    const runningData = message.RunningData||{};
   
    runningData.acquisitionTime = moment().format("YYYY-MM-DD HH:mm:ss");
    setRunningData(runningData);
  }



  useEffect(() => {
    const setSelectData = async () => {
      var details = await getMonitoringDevicInfo({id});
      if (details.deviceInfo) {
          details.deviceInfo.protocol = details.deviceInfo.protocolConfig==null||details.deviceInfo.protocolConfig==""?null:JSON.parse(details.deviceInfo.protocolConfig);
     }
      setRunningData(details.runningData);
      setDeviceInfo(details.deviceInfo);
      
    }
    setSelectData();
    if(dicts){
      setAlarmSourceEnumDict(dicts["5Enum"]);
      setAlarmCategoryEnumDict(dicts["6Enum"]);
      setAlarmLevelEnumDict(dicts["8Enum"])

    }
  }, []);

  const option2 = {
    color: ["#b79fdb", "#2ccacb", "#ffffff"],
    grid: {
      top: 50,
      left: 30,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
     // min:0,  //取0为最小刻度
      // max: 60, //取100为最大刻度
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data
  };
  
  const option3 = {
    color: ["#b79fdb", "#2ccacb", "#ffffff"],
    grid: {
      top: 50,
      left: 50,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
      scale:true,
       min:0,  //取0为最小刻度
  
 
      axisLabel: {
        formatter: '{value}'
      },
      minInterval:1,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series: second.data?.data1
  };


  const columns: ProColumns[] = [

    {
      title: '报警时间',
      dataIndex: 'alarmTime',

    },
    {
      title: '报警类别',
      dataIndex: 'alarmType',
       valueEnum: alarmCategoryEnumDict
    },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum:  alarmLevelEnumDict,
    },
    {
      title: '报警数值',
      dataIndex: 'alarmValue',
    }, {
      title: '信息来源',
      dataIndex: 'defectSource',
      valueEnum: alarmSourceEnumDict,
    },
    {
      title: '处置状态',
      dataIndex: 'state',
      valueEnum: {0:'未处置',1:'已处置'}
    },
    {
      title: '报警处置信息',
      dataIndex: 'alarmAnswer',

    },



    {
      title: '操作',
      dataIndex: 'state',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
       {record.state==0?
        <a onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >处置</a>:null} 
        </>
      )
    },
  ];


  
  return (
    <div className={styles.main} key={1}>
      <Descriptions column={4} title={"设备基本信息"} key={2}>
        <Descriptions.Item label="设备位号">{deviceInfo?.deviceNo}</Descriptions.Item>
        <Descriptions.Item label="设备名称">{deviceInfo?.deviceName}</Descriptions.Item>
        <Descriptions.Item label="设备类型">{deviceInfo?.deviceTypeName}</Descriptions.Item>
        {/* <Descriptions.Item label="驱动名称">{deviceInfo?.driverName}</Descriptions.Item> */}
        {/* <Descriptions.Item label="驱动类型">{deviceInfo?.driverType == 0 ? "网口" : "串口"}</Descriptions.Item> */}
        <Descriptions.Item label="所在区域">{deviceInfo?.areaName}</Descriptions.Item>
        <Descriptions.Item label="所在位置">{deviceInfo?.devicePosition}</Descriptions.Item>
        <Descriptions.Item label="设备描述">{deviceInfo?.deviceDesc}</Descriptions.Item>
        <Descriptions.Item label="设备品牌">{deviceInfo?.deviceBrand}</Descriptions.Item>
        <Descriptions.Item label="设备型号">{deviceInfo?.deviceModel}</Descriptions.Item>
        <Descriptions.Item label="产品序列号">{deviceInfo?.seriaNumber}</Descriptions.Item>
        <Descriptions.Item label="上线时间">{deviceInfo?.onlineTime}</Descriptions.Item>
        <Descriptions.Item label="启用状态">{deviceInfo?.useState == 1 ? '启用' : '未启用'}</Descriptions.Item>
        <Descriptions.Item label="最新维保时间">{deviceInfo?.latestMaintenanceTime}</Descriptions.Item>
        <Descriptions.Item label="供货商">{deviceInfo?.supplier}</Descriptions.Item>
        <Descriptions.Item label="供货商联系人姓名">{deviceInfo?.supplierName}</Descriptions.Item>
        <Descriptions.Item label="供货商联系人电话">{deviceInfo?.supplierPhone}</Descriptions.Item>
        <Descriptions.Item label="驱动名称">{deviceInfo.driverName}</Descriptions.Item>
          <Descriptions.Item label="通讯协议：">{deviceInfo.protocolTypeName}


        
          {deviceInfo?.protocol!=null&&deviceInfo?.protocol!=""?
             <> ( { Object.keys(deviceInfo.protocol).map((item, index) => (
             <> {item}:{deviceInfo.protocol[item]} </>
            ))}) </>:<></>}
         

           </Descriptions.Item>
      </Descriptions>

    

      {/* <Descriptions title={"通讯协议：  " + deviceInfo?.protocolTypeName} column={4} key={3}>
        {deviceInfo?.protocol ? Object.keys(deviceInfo.protocol).map((item, index) => (
          <Descriptions.Item key={index} label={item}>{deviceInfo?.protocol[item]}</Descriptions.Item>
        )) : null}
      </Descriptions> */}
      <Divider className={styles.divider} />
      {/* <Row gutter={[16, 16]} style={{ padding: '0 0 16px 0', color: '#fff' }} key={4}>
        <Col span={24}>数据更新时间：{runningData?.acquisitionTime} </Col>
      </Row> */}

      <RunData type={type} runningData={runningData}></RunData>
       {/* {getRunningDataDom()} */}
      <Row style={{ paddingTop: '8px' }} key={6}>
        <Tabs defaultActiveKey="1" style={{ width: '100%' }}>
          <TabPane tab="历史曲线"  key={1}>
         
           
             {type==1?<>
             <div style={{textAlign:'center'}}>
                <Radio.Group  onChange={(value)=>setChartIndex(value.target.value)} defaultValue={0} buttonStyle="solid">
                  <Radio.Button value={0}>运行频率单位hz</Radio.Button>
                  <Radio.Button value={1}>运行转速（RPM</Radio.Button>
                </Radio.Group>
              </div>
              <ECharts  style={{display:chartIndex==1?'block':'none'}} option={option3} />
              </>:null}
             <ECharts  style={{display:chartIndex==0?'block':'none'}} option={option2} />
          
          
           
         
       
          </TabPane>
          <TabPane tab="报警信息" key={2}>
            <ProTable
              headerTitle=""
              className={styles.alarmTable}
              actionRef={actionRef}
              rowKey="id"
              search={false}
              request={(tableParams) => queryDeviceAlarm({ ...tableParams, ...{ deviceId: id } })}
              columns={columns}
              options={false}
              pagination={{
                defaultCurrent: 1,
                defaultPageSize: 10,
              }}
            />
          </TabPane>
        </Tabs>
      </Row>
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
      
        />
      ) : null}
    </div>
  );
};

export default details;